<?php
/**
 * Created by PhpStorm.
 * User: tjjs
 * Date: 17-6-22
 * Time: 下午3:45
 */

namespace ActionsHttp;

use Data\Tree_customer_info;
use Data\Tree_customer_info_DAO;

class CustomerLoginByWx extends BaseActionHttp
{
    public function doAction()
    {
        // 微信id
        $wx_id = $this->data[CUSTOMER_WX_ID];
        // 用户记录
        $customer_record = Tree_customer_info_DAO::getRecordByWxId($wx_id);
        if (!$customer_record) {
            // 微信新用户
            $customer_record = new Tree_customer_info(array());
            $customer_record->setCUSTOMER_WX_ID($wx_id);
            $customer_record->setLOGIN_TIME(time());
            // 插入
            $customer_id = Tree_customer_info_DAO::insert($customer_record);
            // 随机码
            $rand_str = $this->getRandomString(10);
            // 返回数据
            $this->setValue(CUSTOMER_ID,$rand_str.$customer_id);
            $this->ResponseDataToCurrentClient();
        } else {
            // 老用户
            // 用户id
            $customer_id = $customer_record->getCUSTOMER_ID();
            $customer_record->setLOGIN_TIME(time());
            Tree_customer_info_DAO::update($customer_record);

            // 随机码
            $rand_str = $this->getRandomString(10);
            // 返回数据
            $this->setValue(CUSTOMER_ID,$rand_str.$customer_id);
            $this->ResponseDataToCurrentClient();
        }
    }

    function getRandomString($len, $chars=null)
    {
        if (is_null($chars)){
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }

}